//
//  SureCompleteVC.m
//  Recycling
//
//  Created by jzd on 2018/5/21.
//  Copyright © 2018年 宋佳. All rights reserved.
//

#import "SureCompleteVC.h"
#import "pictureCollectionView.h"
#import <SVProgressHUD.h>

@interface SureCompleteVC ()<UITextViewDelegate,CTAssetsPickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextView *remarkTextV;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollV;
@property (strong,nonatomic)NSMutableArray *imagesArray;
@property (weak, nonatomic) IBOutlet pictureCollectionView *pictureCollectionView;
@property (weak, nonatomic) IBOutlet UIScrollView *bottomScorll;
@property (weak, nonatomic) IBOutlet UILabel *apriceL;
@property (weak, nonatomic) IBOutlet UITextField *priceTextV;

@property (strong,nonatomic)UIImagePickerController *pickerC;

@end

@implementation SureCompleteVC

-(UIImagePickerController *)pickerC{
    if (!_pickerC) {
        _pickerC = [[UIImagePickerController alloc]init];
        _pickerC.allowsEditing = YES;
        _pickerC.delegate = self;
    }
    return _pickerC;
}

-(NSMutableArray *)imagesArray{
    if (_imagesArray == nil) {
        _imagesArray = [NSMutableArray array];
    }
    return _imagesArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"完工确认";
    self.view.backgroundColor = BGCOLOR;
    
    //添加图片
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addPic:) name:addPictureNotification object:nil];
    
    //删除图片
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeImg:) name:delegatePicNotification object:nil];
    
    //监听键盘的弹出
    [self autoScrollViewContentSize];
    
    //是否显示回收价
    [self shouldHiddenAprice];
}
-(void)shouldHiddenAprice{
    NSDictionary *params = @{@"id":@(self.model.ID)};
    [[SJNetWorkTool sharedTool]requestWithURLString:shouldShowActual parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            if (code == 1) {
                self.apriceL.hidden = NO;
                self.priceTextV.hidden = NO;
            }
        }
    }];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)autoScrollViewContentSize{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardHidn:) name:UIKeyboardDidHideNotification object:nil];
}
-(void)keyBoardShow:(NSNotification *)noti{
    if (iphone5) {
        self.bottomScorll.contentSize = CGSizeMake(0, SJScreenH+130);
    }else if (iphone6){
        self.bottomScorll.contentSize = CGSizeMake(0, SJScreenH+80);
    }
    
}
-(void)keyBoardHidn:(NSNotification *)noti{
    self.bottomScorll.contentSize = CGSizeMake(0, SJScreenH);
    [UIView animateWithDuration:0.2 animations:^{
        self.bottomScorll.contentOffset = CGPointMake(0, -(statsBarHeight+NavgationBarH));
    }];
}
- (IBAction)tapScroll:(UITapGestureRecognizer *)sender {
    [self.scrollV endEditing:YES];
}
- (IBAction)completeOnClick:(UIButton *)sender {
    [self.remarkTextV resignFirstResponder];
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    
    if (self.priceTextV.hidden == NO) {
        if (self.priceTextV.text.length == 0) {
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
            [self.navigationController.view showToast:@"请输入实际回收价" completion:nil];
            return;
        }
    }
    
    NSDictionary *dict = @{@"id":@(self.model.ID),
                           @"uid":@([UserInfoTool shareUserInfoTool].Info.ID)
                           };
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dict];
    if (self.remarkTextV.text.length != 0) {
        [params setObject:self.remarkTextV.text forKey:@"note"];
    }
    if (self.imagesArray.count == 0) {
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        [self.navigationController.view showToast:@"请选择图片" completion:nil];
        return;
    }
    
    [[SJNetWorkTool sharedTool]uploadPhoto:self.imagesArray WithURLString:CompleteOrder parameters:params callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            if (code == 1) {
                [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
                [self.navigationController.view showToast:@"完成订单" completion:nil];
                if (self.refreshBlock) {
                    self.refreshBlock(YES);
                }
                //完単 刷新完単的表格
                [[NSNotificationCenter defaultCenter]postNotificationName:wandanNotification object:nil];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                if (self.refreshBlock) {
                    self.refreshBlock(NO);
                }
            }
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        }else{
            if (self.refreshBlock) {
                self.refreshBlock(NO);
            }
        }
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        
        [self completeOnClick:nil];
    }
    return YES;
}
-(void)addPic:(NSNotification *)noti{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择方式" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    UIAlertAction *pai = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if (self.imagesArray.count>=6) {
            [self.navigationController.view showToast:@"最多选6张照片上传!!!" completion:nil];
            return ;
        }
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            [self.navigationController.view showToast:@"相机不可用" completion:nil];
        }else{
            self.pickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.pickerC animated:YES completion:nil];
        }
    }];
    UIAlertAction *xuan = [UIAlertAction actionWithTitle:@"从手机相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
            if (status != PHAuthorizationStatusAuthorized) return;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                // 弹出图片选择界面
                CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
                // 隐藏空相册
                picker.showsEmptyAlbums = NO;
                // 显示图片索引
                picker.showsSelectionIndex = YES;
                picker.assetCollectionSubtypes = @[
                                                   @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                                   @(PHAssetCollectionSubtypeAlbumRegular)
                                                   ];
                picker.delegate = self;
                
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // 如果当前运行的设备是平板电脑
                    picker.modalPresentationStyle = UIModalPresentationFormSheet;
                }
                
                [self presentViewController:picker animated:YES completion:nil];
            });
        }];
    }];
    alert.view.tintColor = TITLECOLOR;
    [alert addAction:pai];
    [alert addAction:xuan];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - <CTAssetsPickerControllerDelegate>
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max = 6;
    if (self.imagesArray) {
        if (picker.selectedAssets.count + self.imagesArray.count  < max) {
            return YES;
            
        }else{
            return NO;
        }
    }else{
        if (picker.selectedAssets.count  < max) {
            return YES;
            
        }else{
            return NO;
        }
    }
    
    
}

/**
 *  选择完毕的时候调用
 */
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 选择图片时的配置项
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode   = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.synchronous = YES;
    // 显示图片
    for (NSInteger i = 0; i < assets.count; i++) {
        PHAsset *asset = assets[i];
        CGSize size = CGSizeMake(asset.pixelWidth / [UIScreen mainScreen].scale, asset.pixelHeight / [UIScreen mainScreen].scale);
        
        // 请求图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            [self.imagesArray addObject:result];
            if (i== assets.count-1) {
                if (self.imagesArray.count>0) {
                    self.pictureCollectionView.images = self.imagesArray.copy;
                }
            }
        }];
    }
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{

    if (self.imagesArray.count>=6) {
        [self.navigationController.view showToast:@"最多选6张照片上传!!!" completion:nil];
        return ;
    }
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    //这里的图片可以是本地图片也可以是网络的图片，网络的需要通过SD转化
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    [self.imagesArray addObject:image];
    self.pictureCollectionView.images = self.imagesArray.copy;
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    SJLog(@"已存入手机相册");
    
}
-(void)removeImg:(NSNotification *)noti{
    UIImage *img = (UIImage *)noti.object;
    [self.imagesArray removeObject:img];
    self.pictureCollectionView.images = self.imagesArray.copy;
}
@end
